/*
 * Copyright 2012 jsm.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package net.abiwebz.office.rm.database.configuration;

import java.awt.Component;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.prefs.Preferences;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
import javax.swing.filechooser.FileFilter;
import javax.swing.filechooser.FileNameExtensionFilter;
import net.abiwebz.office.rm.database.DatabaseDrivers;
import org.openide.DialogDisplayer;
import org.openide.LifecycleManager;
import org.openide.WizardDescriptor;
import org.openide.util.Exceptions;
import org.openide.util.NbPreferences;

public final class DbConfigWizardAction {

    // TODO Update this function to be more "Readable"
    public void execute() {
        List<WizardDescriptor.Panel<WizardDescriptor>> panels = new ArrayList<WizardDescriptor.Panel<WizardDescriptor>>();
        panels.add(new DbConfigWizardPanel1());
        panels.add(new DbConfigWizardPanel2());
        panels.add(new DbConfigWizardPanel3());
        String[] steps = new String[panels.size()];
        for (int i = 0; i < panels.size(); i++) {
            Component c = panels.get(i).getComponent();
            // Default step name to component name of panel.
            steps[i] = c.getName();
            if (c instanceof JComponent) { // assume Swing components
                JComponent jc = (JComponent) c;
                jc.putClientProperty(WizardDescriptor.PROP_CONTENT_SELECTED_INDEX, i);
                jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DATA, steps);
                jc.putClientProperty(WizardDescriptor.PROP_AUTO_WIZARD_STYLE, true);
                jc.putClientProperty(WizardDescriptor.PROP_CONTENT_DISPLAYED, true);
                jc.putClientProperty(WizardDescriptor.PROP_CONTENT_NUMBERED, true);
            }
        }
        WizardDescriptor wiz = new WizardDescriptor(new WizardDescriptor.ArrayIterator<WizardDescriptor>(panels));
        // {0} will be replaced by WizardDesriptor.Panel.getComponent().getName()
        wiz.setTitleFormat(new MessageFormat("{0}"));
        wiz.setTitle("Database configuration");
        if (DialogDisplayer.getDefault().notify(wiz) == WizardDescriptor.FINISH_OPTION) {
            // The configuration is finish so we ask the user if he want to
            // generate a configuration file from the settings
            String onlineID = (String) wiz.getProperty(DbConfigVisualPanel2.PROP_ONLINE_DRIVER);
            String onlineJDBC = (String) wiz.getProperty("online_" + DriverConfigurationPanel.PROP_JDBC_URL);
            boolean offline = (Boolean) wiz.getProperty(DbConfigVisualPanel3.PROP_OFFLINE_CHECK);
            String offlineID = (String) wiz.getProperty(DbConfigVisualPanel2.PROP_ONLINE_DRIVER);
            String offlineJDBC = (String) wiz.getProperty("offline_" + DriverConfigurationPanel.PROP_JDBC_URL);
            boolean imported = (Boolean) wiz.getProperty(DbConfigVisualPanel1.PROP_IMPORT_CHECK);
            if (!imported) {
                int i = JOptionPane.showConfirmDialog(null, "Do you want to generate a configuration file for other clients ?", "Generate configuration", JOptionPane.YES_NO_OPTION);
                if (i == JOptionPane.YES_OPTION) {
                    // Generate file here!
                    Properties config = new Properties();
                    // Online properties
                    config.setProperty("online_driver", onlineID);
                    config.setProperty("online_jdbc_url", onlineJDBC);
                    // Offline properties
                    config.setProperty(DbConfigVisualPanel3.PROP_OFFLINE_CHECK, (offline) ? "1" : "0");
                    if (offline) {
                        config.setProperty("offline_driver", offlineID);
                        config.setProperty("offline_jdbc_url", offlineJDBC);
                    }

                    FileFilter inf = new FileNameExtensionFilter("Informations files (*.inf)", "inf");
                    JFileChooser chooser = new JFileChooser();
                    chooser.addChoosableFileFilter(inf);
                    if (chooser.showSaveDialog(null) == JFileChooser.APPROVE_OPTION) {
                        File configFile = chooser.getSelectedFile();
                        try {

                            config.store(new FileOutputStream(configFile), "");

                        } catch (IOException ex) {
                            Exceptions.printStackTrace(ex);
                        }
                    }
                }
            }

            //Save the configuration into NB config
            Preferences p = NbPreferences.forModule(DatabaseDrivers.class);
            p.putBoolean("database.driver.set", true); // Configuration is finish!
            p.put("database.connection", "online"); // By default use the online connection
            // Online configuration
            p.put("database.driver.online.id", onlineID);
            p.put("database.driver.online.jdbc", onlineJDBC);
            // Offline configuration
            p.putBoolean("database.driver.offline.set", offline);
            if (offline) {
                p.put("database.driver.offline.id", offlineID);
                p.put("database.driver.offline.jdbc", offlineJDBC);
            }

        } else {
            // Configuration is not finished so we quit!
            LifecycleManager.getDefault().exit();
        }
    }
}
